import dayjs from "dayjs";
import { DATE_TIME_FORMATTER } from "@chulei-ui/utils";
import { Service } from "typedi";
import { AuthRole, Role } from "./role/entity";
import { database, esi } from "./index";
import type { AuthUser, Token } from "@scvzerng/esi-163";

import type { Repository } from "typeorm";

@Service()
export class AuthService {
  private authRepository: Repository<AuthRole>;
  constructor() {
    this.authRepository = database.getRepository(AuthRole);
  }

  /**
   * 添加授权角色
   * @param token
   * @param authUser
   */
  addAuthRole(token: Token, authUser: AuthUser) {
    return this.authRepository.save(AuthRole.from(token, authUser));
  }

  /**
   * 续期
   * @param playerId
   */
  async renewToken(playerId: number) {
    const authRole = await this.authRepository.findOne({ where: { id: playerId } });
    const token = await esi.auth.getTokenFromRefreshToken(authRole!.refresh_token);
    if (!token) throw new Error(`refresh token ${token} renew fail`);
    authRole!.access_token = token.access_token;
    authRole!.refresh_token = token.refresh_token;
    authRole!.exp = dayjs().add(token.expires_in, "seconds").subtract(2, "minutes").format(DATE_TIME_FORMATTER);
    const saved = await this.authRepository.save(authRole!);
    return saved!;
  }

  /**
   * 获取访问令牌
   * @param authRole
   */
  async getAccessToken(authRole: AuthRole) {
    if (dayjs(authRole.exp, DATE_TIME_FORMATTER).isBefore(dayjs())) {
      return (await this.renewToken(authRole.id)).access_token;
    }
    return authRole.access_token;
  }

  async getAccessTokenFromPlayerId(playerId: number) {
    const authRole = await this.authRepository.findOne({ where: { id: playerId } });
    return this.getAccessToken(authRole!);
  }

  async getRole(playerId: number) {
    const player = await this.authRepository.findOne({ where: { id: playerId } });
    return new Role(player!);
  }

  /**
   * 获取所有授权角色
   */
  getAuthRoles() {
    return this.authRepository.find({});
  }
}
